package com.kun.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.kun.entity.User;
import com.kun.result.ExceptionMsg;
import com.kun.result.Response;
import com.kun.result.ResponseData;
import com.kun.service.UserService;
import com.kun.util.UploadCosUtil;
/**
 * 用户个人模块controller
 * */
@Controller
@RequestMapping("/my")
public class UserController extends BaseController{
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Value("${application.imgSuffix}")
    private String[] imgSuffix;
	
	@Autowired
	private UserService userServiceImpl;
	
	@InitBinder
	public void initBinder(WebDataBinder binder, WebRequest request) {
		//转换日期
		DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));// CustomDateEditor为自定义日期编辑器
	}
	
	@RequestMapping("")
	public String myInfo(Model model){
		Subject  currentUser = SecurityUtils.getSubject(); 
		User user = (User) currentUser.getPrincipal();
		model.addAttribute("user", user);
		return "userInfo";
	}
	
	
	@RequestMapping(value="/updateUserInfo",method=RequestMethod.POST)
	@ResponseBody
	public Response updateUserInfo(User newUser){
		Subject  currentUser = SecurityUtils.getSubject(); 
		User user = (User) currentUser.getPrincipal();
		if(newUser.getNickname()!=null){
			user.setBirthday(newUser.getBirthday());
			user.setNickname(newUser.getNickname());
			user.setSign(newUser.getSign());
		}else if(newUser.getRealname()!=null){
			user.setRealname(newUser.getRealname());
			user.setIdcard(newUser.getIdcard());
			user.setSex(newUser.getSex());
			user.setAddress(newUser.getAddress());
			user.setPhone(newUser.getPhone());
		}
		int i = userServiceImpl.updateUserByIdSelective(user);
		if(i>0){
			return result(ExceptionMsg.SUCCESS);
		}else{
			return result(ExceptionMsg.FAILED);
		}
	}
	
	
	@RequestMapping(value="uploadImg",method=RequestMethod.POST) 
	@ResponseBody
    public Response UploadUserImg(HttpServletRequest req,MultipartHttpServletRequest multiReq){
		Subject  currentUser = SecurityUtils.getSubject();
		User user = (User) currentUser.getPrincipal();
		try {
			MultipartFile  file = multiReq.getFile("file");
			if (file.isEmpty()) {  
	            return result(ExceptionMsg.FileEmpty);
	        }
			// 获取文件名  
	        String fileName = file.getOriginalFilename();  
	        logger.info("上传的文件名为：" + fileName);  
	        // 获取文件的后缀名  
	        String suffixName = fileName.substring(fileName.lastIndexOf("."));  
	        logger.info("上传的后缀名为：" + suffixName);
	        if(!ArrayUtils.contains(imgSuffix, suffixName)){
	        	//不支持的后缀
	        	return result(ExceptionMsg.LimitPictureType);
	        }
	        String fName = "";
	        String img = user.getHeadImg();
	        String defaultImg = "https://deepfeel-1253391577.cos.ap-guangzhou.myqcloud.com/userImg/default.jpeg";
	        String cosPath = "/userImg/";
	        if(img==null||"".equals(img)||defaultImg.equals(img)){
	        	fName = UUID.randomUUID().toString() + suffixName;
				logger.info("头像上传： newname：" + fName);
	        }else{
	        	fName = user.getHeadImg();
	        	fName = fName.replace("https://deepfeel-1253391577.cos.ap-guangzhou.myqcloud.com"+cosPath, "");
	        	UploadCosUtil.deleteCosPic(cosPath + fName);
	        	fName = UUID.randomUUID().toString() + suffixName;
	        }
	        //上传腾讯云cos
			String url = UploadCosUtil.picCOS(file, cosPath, fName);
			user.setHeadImg(url);
			int i = userServiceImpl.updateUserByIdSelective(user);
	        if(i==0){
	        	return result(ExceptionMsg.FAILED);
	        }
	        return new ResponseData(ExceptionMsg.SUCCESS,url);
		} catch (Exception e) {
			logger.error("failure--"+e.getMessage());
			return result(ExceptionMsg.FAILED);
		}
    }
	
}
